' PRINT "Hello" 100 times ' LET COUNT = 1 DO WHILE COUNT <= 100 PRINT "Hello" LET COUNT = COUNT + 1 LOOP ' END
It is easy to make the change.
And it is much easier to
PRINT
100 "Hellos" with this program than with
one that does not use a loop.
Here is a small but important change to the program:
' PRINT "Hello" 10 times ' LET ENDVALUE = 10 LET COUNT = 1 DO WHILE COUNT <= ENDVALUE PRINT "Hello" LET COUNT = COUNT + 1 LOOP ' END
The first statement saves the value 10 in the variable
ENDVALUE
.
This statement is executed only once, since it is not
part of the loop.
Then the DO WHILE
statement compares the number in COUNT
to the number in ENDVALUE
:
DO WHILE COUNT <= ENDVALUE
Since there is a 10 in ENDVALUE
, this is the same as:
DO WHILE COUNT <= 10
The very first time this is done, COUNT
has a 1 in it,
so this is the same as:
DO WHILE 1 <= 10
So the loop body executes.
Then COUNT
is changed to 2, and the
DO WHILE
test is performed
again:
DO WHILE COUNT <= ENDVALUE ^ ^ | | | +---- holds a 10 | +----- holds a 2 (this time around)
And so on. The loop will work just like it did before,
but now the 10 is kept inside ENDVALUE
rather
put explicitly
in the DO WHILE
test.
The advantage is that the number in ENDVALUE
can be changed,
and then the loop will execute a different number of times.
What will the following program PRINT
out?
' Mystery Program ' LET ENDVALUE = 5 LET COUNT = 1 DO WHILE COUNT <= ENDVALUE PRINT "Hello" LET COUNT = COUNT + 1 LOOP ' END